<template>
  <div class="note-editor">
    <div v-show="context.kind == NoteKind.Note || context.kind == NoteKind.Lecture || context.kind == NoteKind.Intro">
      <div class="note-title">编辑笔记</div>
      <!--<mavon-editor :value="content" @input="content = $event"></mavon-editor>-->
      <md-editor v-model="content"></md-editor>
    </div>
    <div v-show="context.kind == NoteKind.Phonetics">
      <div class="note-title">编辑注音</div>
      <pinyin-input v-model="content"></pinyin-input>
    </div>
    <el-button type="primary" @click="saveNote">保存</el-button>
    <el-button @click="$emit('close')">取消</el-button>
  </div>
</template>

<script>
import {NoteKind} from "@/js/constants.js"
import PinyinInput from "./PinyinInput.vue"
import MdEditor from "@/tools/MdEditor.vue"

export default {
  components: {
    PinyinInput,
    MdEditor,
  },
  props: ["context", "value"],
  data() {
    return {
      NoteKind: NoteKind,
      content: "",
    }
  },
  mounted() {
  },
  methods: {
    onInput() {
      //this.note.content = ev;
      this.$emit('input', this.note)
    },
    saveNote() {
      console.log("start saving note");
      let note = {};
      note.content = this.content;
      var url = "";
      if ("id" in this.context && this.context.id) {
        // modify
        url = "/api/v1/note/modify";
      } else {
        // 新建
        let ctx = this.context;
        if (!ctx.mat || !ctx.mat.id) {
          // 如果当前素材还没有建立数据库选项（例如代码），就需要先调用素材创建接口
          this.authPost("/api/v1/materials/addpath?path="+ctx.mat.title).then(res => {
            let mat = res.data;
            ctx.mat = mat;
            //this.saveNote();
          });
          return;
        }
        note.mid = ctx.mat.id;
        note.mpath = ctx.mat.path;
        note.kind = ctx.kind;
        note.scope = ctx.scope;
        note.line = Number(ctx.line);
        note.spos = ctx.spos;
        note.epos = ctx.epos;
        note.value = ctx.value || 0;
        url = "/api/v1/note/add";
      }

      console.log("saving note:", JSON.stringify(note));
      return this.authPost(url, note)
        .then((res) => {
          let noteid = res.data.id;
          note.id = noteid;
          this.$emit("close");
          return note;
        })
        .catch((error) => {
          console.log(error);
        });
    },
  }
};
</script>

<style lang="stylus">
.note-editor
  padding 20px
  border 1px dashed #eee
  border-radius 4px
  background-color #fafafa

  &>div
    margin-bottom 20px

  .note-title
    font-weight bold
    margin-bottom 20px
</style>